package cn.exrick.xboot.shop.controller;

import cn.exrick.xboot.core.common.utils.PageUtil;
import cn.exrick.xboot.core.common.utils.ResultUtil;
import cn.exrick.xboot.core.common.utils.SecurityUtil;
import cn.exrick.xboot.core.common.vo.PageVo;
import cn.exrick.xboot.core.common.vo.Result;
import cn.exrick.xboot.shop.entity.ShopSwiper;
import cn.exrick.xboot.shop.service.IShopSwiperService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
* <p>
    *   前端控制器
    * </p>
*
* @author yuhaifei
* @since 2021-12-28
*/
@RestController
@RequestMapping("/xboot/shopswiper")
public class ShopSwiperController {

    @Autowired
    private IShopSwiperService swiperService;

    @Autowired
    private SecurityUtil securityUtil;

    @GetMapping("getByCondition")
    public Result<IPage<ShopSwiper>> getByCondition(PageVo pageVo, ShopSwiper swiper){
        Page page = PageUtil.initMpPage(pageVo);
        QueryWrapper<ShopSwiper> wrapper = new QueryWrapper<ShopSwiper>();
        this.setWrapper(wrapper, swiper);

        IPage<ShopSwiper> ipage = swiperService.page(page, wrapper);
        return new ResultUtil<IPage<ShopSwiper>>().setData(ipage);
    }

    public void setWrapper(QueryWrapper wrapper, ShopSwiper swiper){
        if(StrUtil.isNotBlank(swiper.getTitle())){
            wrapper.like("title", swiper.getTitle());
        }

        if(StrUtil.isNotBlank(swiper.getContent())){
            wrapper.like("content", swiper.getContent());
        }

    }

    @PostMapping("save")
    public Result save(ShopSwiper swiper){
        swiper.setCreateBy(securityUtil.getCurrUser().getId());
        swiper.setCreateTime(new Date());
        swiperService.save(swiper);
        return ResultUtil.data("添加成功");
    }

    @PostMapping("update")
    public Result edit(ShopSwiper swiper){
        ShopSwiper target = swiperService.getById(swiper.getId());
        BeanUtil.copyProperties(swiper,target, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));

        swiperService.updateById(target);
        return ResultUtil.data("编辑成功");
    }

    @PostMapping("delByIds")
    public Result delByIds(String ids){
        List idList = Arrays.asList(ids);
        swiperService.removeByIds(idList);
        return ResultUtil.data("删除成功");
    }

            

}
